<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['system:dept:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="tableSelectedData.length !== 1"
          @click="handleUpdate()"
          v-hasPermi="['system:dept:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="tableSelectedData.length !== 1 || tableSelectedData[0].parentId === '0'"
          @click="handleDelete()"
          v-hasPermi="['system:dept:remove']"
        >删除
        </el-button>
      </el-col>
    </el-row>
    <el-table
      class="list-table"
      ref="table"
      v-loading="listLoading"
      :data="listData"
      size="small"
      highlight-current-row
      row-key="deptId"
      :expand-row-keys="defaultExpandedKeys"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
      style="width: 100%;">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="deptName" label="部门名称" width="230px"></el-table-column>
      <el-table-column prop="orderNum" label="排序"></el-table-column>
      <el-table-column prop="chargeNickName" label="负责人">
        <template slot="header" slot-scope="{}">
          <p style="margin: 0;">负责人</p>
        </template>
        <template slot-scope="scope">
          <span>{{ scope.row.chargeNickName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="assistantNickName" label="助理">
        <template slot="header" slot-scope="{}">
          <p style="margin: 0;">助理</p>
        </template>
        <template slot-scope="scope">
          <span>{{ scope.row.assistantNickName || '-' }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" prop="status" label="启用/停用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :disabled="scope.row.parentId === ''"
            active-value="0"
            inactive-value="1"
            @change="handleAvailable(scope, $event)"
          ></el-switch>
        </template>
      </el-table-column>-->
      <el-table-column align="center" prop="createTime" label="创建日期">
        <template slot="header" slot-scope="{}">
          <p style="margin: 0;">创建日期</p>
        </template>
        <template slot-scope="scope">
          <div>{{scope.row.createTime | formatDate('yyyy-MM-dd')}}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="left" label="操作" :width="actionWidth"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary"
                     size="mini"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:dept:edit']"></el-button>
          <!--<el-button type="success"
                     size="mini"
                     icon="el-icon-plus"
                     @click="handleAdd(scope.row)"
                     v-hasPermi="['system:dept:add']"></el-button>-->
          <el-button type="danger"
                     size="mini"
                     icon="el-icon-delete"
                     :disabled="scope.row.parentId === '0'"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['system:dept:remove']"></el-button>
          <slot name="rights" :row-data="scope.row"></slot>
        </template>
      </el-table-column>
    </el-table>
    <!--<div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="searchKey.page" :page-sizes="[10, 20, 50, 100, 200]" :page-size="searchKey.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
      </el-pagination>
    </div>-->
  </div>
</template>

<script>
  // import { cancelAxiosText } from '@/config/config'
  import { debounce } from 'lodash'
  import { deleteDepartmentAPI, updateDepartmentAPI } from '@/api/system/department'
  import filters from '@/filters/filters'
  import tagFilter from '@/filters/tagFilter'

  export default {
    name: 'DepartmentTable',
    mixins: [tagFilter, filters],
    components: {},
    data() {
      return {
        searchKey: {},
        isExpand: true,
        tableSelectedData: [], // 选中的表数据
        listData: [] // 列表数据
      }
    },
    props: {
      data: { // 列表数据
        type: Array,
        required: true,
        default() {
          return []
        }
      },
      searchParams: { // 搜索参数
        type: Object,
        required: true,
        default() {
          return {}
        }
      },
      totalCount: {
        type: [String, Number],
        required: true,
        default: 0
      },
      listLoading: {
        type: [Boolean],
        required: true,
        default: false
      }
    },
    computed: {
      actionWidth() {
        let { permissionValue, baseWidth } = {
          baseWidth: 0,
          permissionValue: ['system:dept:edit', 'system:dept:remove']
        }
        let width = baseWidth
        let all_permission = '*:*:*'
        let permissions = this.$store.getters.permissions
        if (permissionValue.length > 0) {
          let isAllPermission = permissions.some(permission => { // 是否全部权限
            return all_permission === permission
          })
          let existingPermissions = permissions.filter(permission => { // 存在的权限
            return permissionValue.includes(permission)
          })
          if (isAllPermission) {
            width += permissionValue.length * 60
          } else {
            width += existingPermissions.length * 60
          }
        }
        return width
      },
      defaultExpandedKeys() {
        let { listData } = this
        let allKeys = this.getKeys(listData)
        /* departmentAllListData.forEach((item, index) => {
          let keys = this.getKeys(item.children)
          allKeys = [...allKeys, ...keys]
        }) */
        return allKeys
      }
    },
    methods: {
      getKeys(data) {
        let filterData = data.filter((item) => {
          return item.children && item.children.length > 0
        })
        return filterData.map(item => item.deptId)
      },
      handleSizeChange(val) { // 分页改变每页条数
        this.searchKey.size = val
        this.$emit('on-init', this.searchKey)
      },
      handleCurrentChange(val) { // 分页切换分页
        this.searchKey.page = val
        this.$emit('on-init', this.searchKey)
      },
      handleSelectionChange(selection) { // 多选框选中数据
        this.tableSelectedData = selection
      },
      handleAdd(data = null) { // 新增按钮操作
        this.$emit('on-edit', data)
      },
      handleUpdate(data = null) { // 修改按钮操作
        let { tableSelectedData } = this
        this.$emit('on-edit', data || tableSelectedData[0])
      },
      /* handleDelete(data = null) { // 删除
        let { tableSelectedData } = this
        this.$emit('on-delete', data || tableSelectedData[0])
      },
      handleEdit(data = null) { // 编辑－显示弹出框
        this.$emit('on-edit', data)
      }, */
      handleAvailable(data, value) { // 启用/停用
        this.$confirm(`此操作将 "${value === '0' ? '启用' : '停用'}" ${data.row.deptName}部门, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.availableDepartmentData(data.row, value)
        }).catch(() => {
          data.row.status = value === '0' ? '1' : '0'
          this.$message({
            type: 'info',
            message: '已取消操作!'
          })
        })
      },
      handleDelete(data = null) { // 删除
        this.$confirm('确定要删除吗？,如果存在下级节点则一并删除！！！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteDepartmentData([data.deptId])
        }).catch(() => {
        })
      },
      handleExpand: debounce(function() { // 查询，防抖
        this.isExpand = !this.isExpand
        this.$emit('on-init', this.searchKey)
      }, 300),
      async availableDepartmentData(data, value) { // 启用/停用－请求数据
        try {
          let response = await updateDepartmentAPI(data)
          let result = response
          if (+result.code === 200) {
            this.$notify({
              title: '成功',
              message: `${value === '0' ? '启用' : '停用'}成功！`,
              type: 'success',
              duration: 2000
            })
            this.$emit('update')
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '操作失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          data.status = value === '0' ? '1' : '0'
          this.$notify.error({
            title: '错误',
            message: error.message || '操作失败！'
          })
        }
      },
      async deleteDepartmentData(ids = []) { // 删除-数据请求
        try {
          let response = await deleteDepartmentAPI({
            ids
          })
          let result = response
          if (+result.code === 200) {
            this.$emit('on-init', this.searchKey)
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '删除失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '删除失败!'
          })
        }
      }
    },
    watch: {
      data: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.listData)) {
            this.listData = JSON.parse(JSON.stringify(newVal))
          }
        },
        immediate: true
      },
      searchParams: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
            this.searchKey = JSON.parse(JSON.stringify(newVal))
          }
        },
        immediate: true
      }
    },
    created() {
    },
    mounted() {
    }
  }
</script>

<style lang="scss" scoped>
  .list-table {
    .el-button--mini {
      padding: 7px 15px;
      width: 45px;
      color: #fff;
    }

    & /deep/ .el-table__header-wrapper {
      th {
        background-color: #fff;
      }
    }
  }
</style>
